package com.szcatic.ework.realm;

import java.sql.Connection;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;

import com.szcatic.ework.service.UserService;
import com.szcatic.ework.utils.DBUtils;
import com.szcatic.ework.vo.User;

/**
 * 自定义Realm
 * @author Administrator
 *
 */
@Service("customRealm")
public class CustomRealm extends AuthorizingRealm{
	
	@Resource
	private UserService userService;

	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		String userName = (String)arg0.getPrimaryPrincipal();
		SimpleAuthorizationInfo aInfo = new SimpleAuthorizationInfo();
		try {
			//添加角色信息
			aInfo.setRoles(userService.getRolesByUserName(userName));
			//添加权限信息
			aInfo.setStringPermissions(userService.getPermisionsByUserName(userName));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return aInfo;
	}
	
	/**
	 * 身份认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String userName = (String)token.getPrincipal();
		Connection con = null;
		try {
			User user = userService.getUserByUserName(userName);
			if(user == null) {
				return null;
			} else {
				AuthenticationInfo auInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "myRealm");
				return auInfo;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				DBUtils.closeConnection(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}

	

}
